package com.egao.platform.system.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.egao.platform.common.core.BaseController;
import com.egao.platform.common.core.JsonResult;
import com.egao.platform.common.core.PageParam;
import com.egao.platform.common.core.PageResult;
import com.egao.platform.common.annotation.ApiPageParam;
import com.egao.platform.common.exception.BusinessException;
import com.egao.platform.system.entity.Authorities;
import com.egao.platform.system.entity.RoleAuthorities;
import com.egao.platform.system.service.AuthoritiesService;
import com.egao.platform.system.service.RoleAuthoritiesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangfan on 2018-12-24 16:10
 */
@Api(tags = "权限管理")
@RestController
@RequestMapping("/api/sys/authorities")
public class AuthoritiesController extends BaseController {
    @Autowired
    private AuthoritiesService authoritiesService;
    @Autowired
    private RoleAuthoritiesService roleAuthoritiesService;

    @ApiOperation("分页查询权限")
    @ApiPageParam
    @GetMapping("/page")
    public PageResult<Authorities> page(HttpServletRequest request) {
        PageParam<Authorities> pageParam = new PageParam<>(request);
        pageParam.setDefaultOrder(new String[]{"sort_number"}, null);
        List<Authorities> authorities = authoritiesService.page(pageParam, pageParam.getWrapper("roleId")).getRecords();
        // 回显角色授权选中状态
        authoritiesService.selectRoleChecked(authorities, pageParam.getInt("roleId"));
        return new PageResult<>(authorities, pageParam.getTotal());
    }

    @ApiOperation("查询全部权限")
    @GetMapping()
    public JsonResult list(HttpServletRequest request) {
        PageParam<Authorities> pageParam = new PageParam<>(request);
        pageParam.setDefaultOrder(new String[]{"sort_number"}, null);
        List<Authorities> authorities = authoritiesService.list(pageParam.getWrapper("roleId"));
        // 回显角色授权选中状态
        authoritiesService.selectRoleChecked(authorities, pageParam.getInt("roleId"));
        return JsonResult.ok().setData(authorities);
    }

    @ApiOperation("同步权限")
    @PostMapping("/sync")
    public JsonResult sync() {
        authoritiesService.remove(null);
        authoritiesService.saveBatch(authoritiesService.scan());
        roleAuthoritiesService.deleteTrash();
        return JsonResult.ok("同步成功");
    }

    @ApiOperation("添加角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "authority", value = "权限标识", required = true, dataType = "string")
    })
    @PostMapping("/role/{id}")
    public JsonResult addRoleAuth(@PathVariable("id") Integer roleId, String authority) {
        RoleAuthorities roleAuth = new RoleAuthorities();
        roleAuth.setRoleId(roleId);
        roleAuth.setAuthority(authority);
        if (roleAuthoritiesService.save(roleAuth)) {
            return JsonResult.ok();
        }
        return JsonResult.error();
    }

    @ApiOperation("移除角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "authority", value = "权限标识", required = true, dataType = "string")
    })
    @DeleteMapping("/role/{id}")
    public JsonResult removeRoleAuth(@PathVariable("id") Integer roleId, String authority) {
        if (roleAuthoritiesService.remove(new UpdateWrapper<RoleAuthorities>()
                .eq("role_id", roleId).eq("authority", authority))) {
            return JsonResult.ok();
        }
        return JsonResult.error();
    }

    @ApiOperation("批量修改角色权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "authority", value = "权限标识", required = true, dataType = "string")
    })
    @PutMapping("/role/{id}")
    public JsonResult setRoleAuth(@PathVariable("id") Integer roleId, @RequestBody List<String> authorityList) {
        if (roleAuthoritiesService.remove(new UpdateWrapper<RoleAuthorities>().eq("role_id", roleId))) {
            List<RoleAuthorities> roleAuthList = new ArrayList<>();
            for (String authority : authorityList) {
                RoleAuthorities roleAuth = new RoleAuthorities();
                roleAuth.setRoleId(roleId);
                roleAuth.setAuthority(authority);
                roleAuthList.add(roleAuth);
            }
            if (roleAuthoritiesService.saveBatch(roleAuthList)) {
                return JsonResult.ok();
            } else {
                throw new BusinessException("操作失败");
            }
        }
        return JsonResult.error();
    }

}
